package com.cat.model.biz.service.admin.impl;

import java.io.File;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alonew.core.commons.tuple.TwoTuple;
import com.alonew.db.dao.TxCommonDAO;
import com.cat.model.biz.service.admin.BannerService;
import com.cat.model.common.model.common.BannerVO;
import com.cat.model.common.util.FileUtil;
import com.cat.model.common.util.StaticFileUtil;

@Service("BannerService")
public class BannerServiceImpl implements BannerService{
	@Autowired
	private TxCommonDAO commonDAO;
	
	@Override
	public BannerVO createBanner(BannerVO banner, File image,
			String imageFileName){
		if(image != null){
			String imagePath = StaticFileUtil.bannerRelativePath() + FileUtil.buildDatePath();
			TwoTuple<String, byte[]> md5AndData = FileUtil.readAndCalMd5(image);
			FileUtil.writeFile(StaticFileUtil.staticRootPath() + imagePath, imageFileName, md5AndData.second);
			banner.setImage(imagePath + "/" + imageFileName);
		}
		
		commonDAO.insert(banner);
		
		return banner;
	}
	
	@Override
	public int deleteBanner(long id){
		BannerVO banner = new BannerVO();
		banner.setId(id);
		return commonDAO.deleteById(banner);
	}
	
	@Override
	public int updateBanner(BannerVO banner, File image,
			String imageFileName){
		if(image != null){
			String imagePath = StaticFileUtil.bannerRelativePath() + FileUtil.buildDatePath();
			TwoTuple<String, byte[]> md5AndData = FileUtil.readAndCalMd5(image);
			FileUtil.writeFile(StaticFileUtil.staticRootPath() + imagePath, imageFileName, md5AndData.second);
			banner.setImage(imagePath + "/" + imageFileName);
		}
		
		return commonDAO.updateById(banner, "cityCode", "image","orderIndex","name","bannerType","url","richDesc");
	}
}
